<template>
  <div>
    <a-card>
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="5" :sm="24">
              <a-form-item label="用户名">
                <a-input v-model="queryParam.f_username" placeholder="请输入用户名" />
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item label="姓名">
                <a-input v-model="queryParam.f_fullname" placeholder="请输入姓名" />
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item label="操作">
                <a-input v-model="queryParam.f_action" placeholder="请输入操作" />
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item label="请求内容">
                <a-input v-model="queryParam.f_content" placeholder="请输入请求内容" />
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button v-auth:ha_log_list type="primary" @click="searchHa_log" icon="search">查询</a-button>
                <a-button v-auth:ha_log_list icon="reload" style="margin-left: 8px" @click="reQuery">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div style="margin-bottom: 16px">
        <a-button v-auth:ha_log_list type="primary" @click="exportExcel" icon="export"
          >导出日志</a-button
        >
      </div>
      <a-table
        :scroll="{ x: 1500, y: 500 }"
        :columns="ucolumns"
        :data-source="udata"
        :pagination="upagination"
        :loading="loading"
        rowKey="id"
        @change="tableChange"
        size="middle"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ (upagination.current - 1) * upagination.pageSize + parseInt(index) + 1 }}
        </span>
        <div slot="contentBox" slot-scope="text, record" class="contentBox">
          <a-tooltip placement="topLeft">
            <template slot="title">
              <span>{{ record.content }}</span>
            </template>
            <span>{{ record.content }}</span>
          </a-tooltip>
        </div>
        <span slot="operation" slot-scope="text, record">
          <template v-auth:ha_log_view>
            <a @click="handleEdit(record, true)">详情</a>
          </template>
        </span>
      </a-table>
    </a-card>
    <a-drawer
      :title="isView ? '日志详情' : '日志编辑'"
      :width="720"
      :visible="visible"
      :body-style="{ paddingBottom: '80px' }"
      @close="onClose"
      destroyOnClose
    >
      <edit ref="view" @close="onClose" @reloadList="searchHa_log"></edit>
    </a-drawer>
  </div>
</template>

<style lang="less" src="@/style/base.less">
</style>

<script>
import { delHa_logs, delHa_log, viewHa_log, saveHa_log, queryHa_logList, output } from '@/api/base/ha_log'
import edit from '@/views/base/Ha_logEdit'
// 没有用到枚举作为查询条件的请删除
import { queryEnumerationValuesByName } from '@/api/base/enumeration'

export default {
  data() {
    return {
      advanced: false, // 查询条件是否展开
      loading: false, // 遮罩是否显示
      visible: false, // 抽屉是否可见
      ubordered: true, // 表格边框是否显示
      isView: false, // 是否查看
      queryParam: {}, // 查询条件
      selectedRowKeys: [], // 选中的行id
      udata: [], // 表格数据
      upagination: {
        // 表格分页参数
        defaultPageSize: 20,
        total: 0,
        current: 1,
        pageSize: 20,
        showTotal: (total) => `共${total}条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
      },
      ucolumns: [
        {
          title: '序号',
          width: '80px',
          align: 'center',
          fixed: 'left',
          scopedSlots: { customRender: 'serial' },
        },
        {
          title: '用户名',
          dataIndex: 'username',
          width: '10%',
          sorter: (a, b) => String(a.username).localeCompare(String(b.username)),
          align: 'left',
        },
        {
          title: '姓名',
          dataIndex: 'fullname',
          width: '10%',
          sorter: (a, b) => String(a.fullname).localeCompare(String(b.fullname)),
          align: 'left',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '10%',
          align: 'left',
        },
        {
          title: '请求内容',
          dataIndex: 'contentBox',
          width: '1',
          align: 'content',
          ellipsis: true,
          scopedSlots: {
            customRender: 'contentBox',
          },
        },
        {
          title: '请求时间',
          dataIndex: 'reqtime',
          width: '10',
          sorter: (a, b) => String(a.reqtime).localeCompare(String(b.reqtime)),
          align: 'center',
        },
        {
          title: 'IP',
          dataIndex: 'ip',
          width: '10',
          sorter: (a, b) => String(a.ip).localeCompare(String(b.ip)),
          align: 'left',
        },
        {
          title: '操作',
          width: '150px',
          fixed: 'right',
          scopedSlots: { customRender: 'operation' },
        },
      ], // 表头
    }
  },
  created() {
    // 没有用到枚举作为查询条件的请删除
    this.findEnumByName()
    this.findHa_logList(this.queryParam)
  },
  methods: {
    /**
     *  查询枚举值,没有用到枚举作为查询条件的请删除
     */
    findEnumByName() {
      const parameter = []
      parameter.forEach((item) => {
        queryEnumerationValuesByName({ enName: item.enumName }).then((res) => {
          console.log('query' + item.enumName, res.data)
          this[`${item.enname}List`] = res.data
          this[`${item.enname}List`].unshift({ id: '', description: '全部' })
          console.log(this[`${item.enname}List`])
        })
      })
    },
    /**
     *  查询日志列表
     */
    findHa_logList(queryParam) {
      const a = Date.now()
      console.log('queryParam', queryParam)
      queryHa_logList(queryParam).then((res) => {
        this.loading = true
        console.log('queryHa_logList:', res.data)
        this.udata = res.data.records
        // 将当前页码和数量与后台绑定
        this.upagination.total = res.data.total
        this.upagination.current = res.data.current
        this.upagination.pageSize = res.data.size
        // 如果查询时间太短就给一个0.5秒的加载效果
        const b = Date.now()
        if (b - a < 500) {
          setTimeout(() => {
            this.loading = false
          }, 500)
        } else {
          this.loading = false
        }
      })
    },
    /**
     * 重置查询条件并查询数据
     */
    reQuery() {
      this.queryParam = {}
      this.findHa_logList(this.queryParam)
    },
    /**
     * 翻页、设置页数量时触发，将分页组建的当前页与大小传给后台
     */
    tableChange(pagination, filters, sorter, { currentDataSource }) {
      console.log('tableChange', pagination)
      console.log('filters', filters)
      console.log('sorter', sorter)
      console.log('{ currentDataSource }', { currentDataSource })
      this.queryParam.pageNumber = pagination.current
      this.queryParam.pageSize = pagination.pageSize
      if (sorter != null && sorter.order != null) {
        this.queryParam.sort = sorter.field
        this.queryParam.order = sorter.order
      }
      this.findHa_logList(this.queryParam)
    },
    /**
     * 查询
     */
    searchHa_log() {
      // 查询时将当前页码重置为1，否则会出现有数据但不显示的问题
      this.queryParam.pageNumber = 1
      // this.upagination.current = 1
      this.findHa_logList(this.queryParam)
    },
    /**
     * 选中行数据时触发
     */
    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
    /**
     * 打开抽屉
     */
    showDrawer() {
      this.visible = true
    },
    /**
     * 收回抽屉
     */
    onClose() {
      this.visible = false
    },
    /**
     * 进入新增页面
     */
    handleAdd() {
      this.showDrawer()
      setTimeout(() => {
        this.$refs.view.resetHa_log()
      }, 10)
    },
    /**
     * 进入编辑页面
     */
    handleEdit(res, isView) {
      this.isView = isView
      console.log('view', res.id)
      this.showDrawer()
      setTimeout(() => {
        this.$refs.view.findHa_logById(res.id, isView)
      }, 10)
    },
    /**
     * 删除日志
     */
    delHa_logById(res) {
      delHa_log(res.id).then((res) => {
        console.log('delHa_log:', res)
        if (res.code !== 0) {
          this.$message.success(res.msg)
        } else {
          this.selectedRowKeys = []
          this.searchHa_log()
          this.$message.success('删除成功')
        }
      })
    },
    /**
     * 批量删除日志
     */
    delHa_logs() {
      delHa_logs(this.selectedRowKeys.toString()).then((res) => {
        console.log('delHa_logs:', res)
        if (res.code !== 0) {
          this.$message.success(res.msg)
        } else {
          this.selectedRowKeys = []
          this.searchHa_log()
          this.$message.success('删除成功')
        }
      })
    },
    /**
     *  导出Excel
     */
    exportExcel() {
      output(this.queryParam)
        .then((response) => {
          var blob = new Blob([response])
          var downloadElement = document.createElement('a')
          var href = window.URL.createObjectURL(blob) //创建下载的链接
          downloadElement.href = href
          downloadElement.download = '日志.xls' //下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() //点击下载
          document.body.removeChild(downloadElement) //下载完成移除元素
          window.URL.revokeObjectURL(href) //释放掉blob对象
        })
        .catch(function () {
          console.log(error)
        })
    },
  },
  components: {
    edit,
  },
}
</script>
<style scoped>
.contentBox {
  width: 300px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>